const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const FavoriteLocation = require('../models/FavoriteLocation');

// Get all favorite locations
router.get('/', auth, async (req, res) => {
  try {
    const favorites = await FavoriteLocation.find({ user: req.user._id });
    res.json(favorites);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching favorite locations' });
  }
});

// Add favorite location
router.post('/', auth, async (req, res) => {
  try {
    const { location } = req.body;

    // Check if location already exists
    const existingFavorite = await FavoriteLocation.findOne({
      user: req.user._id,
      location
    });

    if (existingFavorite) {
      return res.status(400).json({ message: 'Location already in favorites' });
    }

    const favorite = new FavoriteLocation({
      location,
      user: req.user._id
    });

    await favorite.save();
    res.status(201).json(favorite);
  } catch (error) {
    res.status(500).json({ message: 'Error adding favorite location' });
  }
});

// Remove favorite location
router.delete('/:id', auth, async (req, res) => {
  try {
    const favorite = await FavoriteLocation.findOneAndDelete({
      _id: req.params.id,
      user: req.user._id
    });

    if (!favorite) {
      return res.status(404).json({ message: 'Favorite location not found' });
    }

    res.json({ message: 'Favorite location removed' });
  } catch (error) {
    res.status(500).json({ message: 'Error removing favorite location' });
  }
});

module.exports = router; 